import api from '../../api/api'
import Toast from '@vant/weapp/toast/toast'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tk: wx.getStorageSync('token') ? wx.getStorageSync('token') : '',
    cartList: [],
    total: 0,
    show: false,
    checked: false,
    allChecked: false
  },

  async getCartListData() {
    const res = await api.getCartList({ tokenString: this.data.tk })
    if (res.data.code == 5000) {
      if (res.data.result.length > 0) {
        res.data.result.forEach((v) => {
          v.checked = false
        })
      }
      this.setData({
        cartList: res.data.result
      })
      console.log('购物车列表', res)
    } else {
      app.checkLogin()
    }
  },
  // 计算总价格
  sum() {
    let a = 0
    this.data.cartList.forEach((item) => {
      if (item.checked) {
        a += item.price * item.count
        this.setData({
          total: a * 100
        })
      }
    })
    this.setData({
      total: a * 100
    })
  },
  // 单选
  check(e) {
    // this.sum()
    let index = e.currentTarget.dataset.index
    let detail = e.detail
    this.setData({
      ['cartList[' + index + '].checked']: detail
    })
    // if (this.data.cartList[index].checked) {
    //   console.log('选中');
    //   this.sum()
    // } else {
    //   console.log('未选中');
    //   this.sum()
    // }
    this.sum()
    let allChecked = this.data.cartList.every(item => item.checked)
    this.setData({
      allChecked: allChecked
    })
  },

  // 全选
  checkAll(e) {
    let detail = e.detail
    this.setData({
      allChecked: detail
    })
    this.data.cartList.forEach((item, index) => {
      this.setData({
        ['cartList[' + index + '].checked']: detail
      })
      item.checked = this.data.allChecked
    })
    if (this.data.allChecked) {
      this.sum()
    } else {
      this.setData({
        total: 0
      })
    }
  },
  // 提交订单/删除选择  按钮显示
  edit() {
    this.setData({
      show: !this.data.show,
    })
    if (this.show == true) {
      this.data.cartList.forEach((v) => {
        v.checked = false
      })
      this.setData({
        allChecked: false
      })
    }
  },
  // 修改数量
  async changeNum(e) {
    let item = e.currentTarget.dataset.item
    let index = e.currentTarget.dataset.index; // 获取当前商品在 cartList 中的索引
    const res = await api.changeCartCount({ tokenString: wx.getStorageSync('token'), sid: item.sid, count: e.detail })
    if (res.data.code == 6000) {
      console.log("修改数量", res)
      Toast.success(res.data.msg)
      this.setData({
        ['cartList[' + index + '].count']: e.detail
      })
      this.sum()
    }
  },
  // 删除购物车（一个或多个）
  async del(sids) {
    const res = await api.deleteCart({ tokenString: wx.getStorageSync('token'), sids })
    if (res.data.code == 7000) {
      Toast.success(res.data.msg)
      this.getCartListData()
    }
  },
  // 单删购物车
  removeOne(e) {
    let index = e.currentTarget.dataset.index
    let sid = e.currentTarget.dataset.sid
    this.data.cartList.splice(index, 1)
    // this.del([sids])
    this.del(JSON.stringify([sid]))
    this.sum()
    this.getCartListData()
  },
  // 多删购物车
  removeMore() {
    const arr = []
    this.data.cartList.forEach((v) => {
      if (v.checked) {
        arr.push(v.sid)
      }
    })
    this.del(JSON.stringify([arr]))
    this.sum()
    this.getCartListData()
    this.setData({
      allChecked: false,
      total: 0
    })
  },

  onSubmit() {
    if (this.data.show) {
      this.data.cartList.forEach((v) => {
        if (v.checked) {
          this.removeMore()
        }
      })
    } else {
      // 把选中的商品sids带到订单页
      let arr1 = []
      this.data.cartList.forEach((v) => {
        if (v.checked) {
          arr1.push(v.sid)
        }
      })
      if (arr1.length < 1) {
        Toast.fail('至少选择一件商品')
        return
      }
      wx.navigateTo({
        url: '/pages/orders/orders?sids=' + arr1 + '&timer=' + new Date().getTime(),
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getCartListData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getCartListData()
    this.setData({
      checked: false,
      allChecked: false,
      total: 0
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})